//TreeMapTest.java
package com.ylaihui.mapitf;

import java.util.*;

class Order implements Comparable{
    int id;
    Date date;

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", date=" + date +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Order order = (Order) o;
        return id == order.id &&
                Objects.equals(date, order.date);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, date);
    }

    public Order(int id, Date date) {
        this.id = id;
        this.date = date;
    }

    public Order() {
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof Order){
            Order order = (Order) o;
            return -(this.id - order.id);
        }else
            throw new RuntimeException("不能比较的类型");
    }

}

public class TreeMapTest {
    public static void main(String[] args) {
        java.util.TreeMap map = new java.util.TreeMap();

        Order o1 = new Order(111, new Date());
        Order o2 = new Order(222, new Date());
        Order o3 = new Order(333, new Date());
        Order o4 = new Order(444, new Date());

        map.put(o1,"o1");
        map.put(o2,"o2");
        map.put(o3,"o3");
        map.put(o4,"o4");

        Set set = map.entrySet();
        Iterator it = set.iterator();
        while (it.hasNext()){
            Object next = it.next();
            Map.Entry entry = (Map.Entry) next;
            System.out.println( entry.getKey() +":"+entry.getValue());
        }

    }
}
